package kr.saeildamil.androidStudy_second.fileio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import kr.saeildamil.androidStudy_second.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class SDCard extends Activity {
	EditText mEdit;
	String mSdPath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch25_sdcard);

		mEdit = (EditText) findViewById(R.id.edittext);

		String ext = Environment.getExternalStorageState();
		prnStat(ext);

		if (ext.equals(Environment.MEDIA_MOUNTED)) {
			mSdPath = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
			prnStat(mSdPath);
		} else {
			mSdPath = Environment.MEDIA_UNMOUNTED;
		}
	}

	public void mOnClick(View v) {
		switch (v.getId()) {
		case R.id.test:
			String rootdir = Environment.getRootDirectory().getAbsolutePath();
			String datadir = Environment.getDataDirectory().getAbsolutePath();
			String cachedir = Environment.getDownloadCacheDirectory()
					.getAbsolutePath();
			String text = String.format("ext = %s\nroot=%s\ndata=%s\ncache=%s",
					mSdPath, rootdir, datadir, cachedir);
			mEdit.setText(text);
			break;
			
		case R.id.save:
			File dir = new File(mSdPath + "/dir");
			dir.mkdir();
			File file = new File(mSdPath + "/dir/fileio.txt");
			try {
				FileOutputStream fos = new FileOutputStream(file);
				String str = "this File exists in SDCard";
				fos.write(str.getBytes());
				fos.close();
				mEdit.setText("Write Success");
			} catch (FileNotFoundException e) {
				mEdit.setText("File Not Founded");
			} catch (IOException e) {
				mEdit.setText(e.getMessage());
			} catch (SecurityException e) {
				mEdit.setText("SecurityException");
			}
			break;
			
		case R.id.load:
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(mSdPath + "/dir.fileio.txt");
				byte[] data = new byte[fis.available()];
				fis.read(data);
				mEdit.setText(new String(data));
			} catch (FileNotFoundException e) {
				mEdit.setText("File Not Founded");
			} catch (IOException e) {
				mEdit.setText(e.getMessage());
			} finally {
				try {fis.close();} catch (IOException e) {}
			}	
			break;
		}
	}

	private void prnStat(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}
}
